package radio.vnmedia.vn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import radio.vnmedia.vn.utils.HTMLUtils;
import radio.vnmedia.vn.utils.SrcGrabber;
import radio.vnmedia.vn.utils.StringUtils;
import radio.vnmedia.vn.utils.htmlparser.FindBarrier;
import radio.vnmedia.vn.utils.htmlparser.FindToFocus;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class RadioVnMedia extends Activity implements Defines {

	// Use static to keep value when itself was onCreate from PlayerScreen
	private static ArrayList<HashMap<String, Object>> m_list_categories = new ArrayList<HashMap<String, Object>>();
	private static ArrayList<HashMap<String, Object>> m_list_subCategories = new ArrayList<HashMap<String, Object>>();
	private static ArrayList<HashMap<String, Object>> m_list_newest = new ArrayList<HashMap<String, Object>>();
	private static ArrayList<HashMap<String, Object>> m_list_tophit = new ArrayList<HashMap<String, Object>>();
	public static ArrayList<HashMap<String, Object>> m_list_current_playlist = new ArrayList<HashMap<String, Object>>();

	// Begin note: Does not set static for below variants. It will be crash
	// randomly. Because it does not synchronize with data.
	private ListView m_listview;
	private SimpleAdapter m_adapter_category;
	private SimpleAdapter m_adapter_subCategory;
	private SimpleAdapter m_adapter_newest;
	private SimpleAdapter m_adapter_tophit;
	// End note

	private ArrayList<String> FF_open_chude = new ArrayList<String>();
	private ArrayList<String> FF_close_chude = new ArrayList<String>();
	private ArrayList<String> FB_open_chude = new ArrayList<String>();
	private ArrayList<String> FB_close_chude = new ArrayList<String>();

	private ArrayList<String> FF_open_moinhat = new ArrayList<String>();
	private ArrayList<String> FF_close_moinhat = new ArrayList<String>();
	private ArrayList<String> FB_open_moinhat = new ArrayList<String>();
	private ArrayList<String> FB_close_moinhat = new ArrayList<String>();

	private ArrayList<String> FF_open_noibat = new ArrayList<String>();
	private ArrayList<String> FF_close_noibat = new ArrayList<String>();
	private ArrayList<String> FB_open_noibat = new ArrayList<String>();
	private ArrayList<String> FB_close_noibat = new ArrayList<String>();

	private ArrayList<String> FF_open_radiotrack = new ArrayList<String>();
	private ArrayList<String> FF_close_radiotrack = new ArrayList<String>();
	private ArrayList<String> FB_open_radiotrack = new ArrayList<String>();
	private ArrayList<String> FB_close_radiotrack = new ArrayList<String>();

	private ArrayList<String> FF_open_totalpages = new ArrayList<String>();
	private ArrayList<String> FF_close_totalpages = new ArrayList<String>();
	private ArrayList<String> FB_open_totalpages = new ArrayList<String>();
	private ArrayList<String> FB_close_totalpages = new ArrayList<String>();

	private ArrayList<String> FF_open_totaltracks = new ArrayList<String>();
	private ArrayList<String> FF_close_totaltracks = new ArrayList<String>();
	private ArrayList<String> FB_open_totaltracks = new ArrayList<String>();
	private ArrayList<String> FB_close_totaltracks = new ArrayList<String>();

	// set static variant to use in PlayerScreen
	public static ArrayList<String> FF_open_radio_playing_image = new ArrayList<String>();
	public static ArrayList<String> FF_close_radio_playing_image = new ArrayList<String>();
	public static ArrayList<String> FB_open_radio_playing_image = new ArrayList<String>();
	public static ArrayList<String> FB_close_radio_playing_image = new ArrayList<String>();

	public static ArrayList<String> FF_open_radio_playing_media = new ArrayList<String>();
	public static ArrayList<String> FF_close_radio_playing_media = new ArrayList<String>();
	public static ArrayList<String> FB_open_radio_playing_media = new ArrayList<String>();
	public static ArrayList<String> FB_close_radio_playing_media = new ArrayList<String>();

	public static ArrayList<String> FF_open_radio_playing_description = new ArrayList<String>();
	public static ArrayList<String> FF_close_radio_playing_description = new ArrayList<String>();
	public static ArrayList<String> FB_open_radio_playing_description = new ArrayList<String>();
	public static ArrayList<String> FB_close_radio_playing_description = new ArrayList<String>();

	public static ArrayList<String> FF_open_radio_playing_luotnghe = new ArrayList<String>();
	public static ArrayList<String> FF_close_radio_playing_luotnghe = new ArrayList<String>();
	public static ArrayList<String> FB_open_radio_playing_luotnghe = new ArrayList<String>();
	public static ArrayList<String> FB_close_radio_playing_luotnghe = new ArrayList<String>();

	public static ArrayList<String> FF_open_radio_playing_name = new ArrayList<String>();
	public static ArrayList<String> FF_close_radio_playing_name = new ArrayList<String>();
	public static ArrayList<String> FB_open_radio_playing_name = new ArrayList<String>();
	public static ArrayList<String> FB_close_radio_playing_name = new ArrayList<String>();

	// private static String mURL;
	private static int int_current_state = STATE_TAB_CATEGORY;// default
	public static HashMap<String, String> HtmlEntity;

	private ProgressDialog mDialog;
	private static String string_HtmlContent;

	private static TextView header_title;
	private static TextView page_info;
	private LinearLayout layout_page_navigation_panel;
	// private LinearLayout layout_playlist_controller_panel;
	private Animation anim_switch_page_enter;
	private Animation anim_switch_page_exit;
	private EditText editbox_page_number;
	private static String string_SubCategoryCurrentPageURL;
	private static String string_current_page = "1";
	private int int_total_pages;
	private static int int_CurrentCategoryIndex = -1;// no categories choose

	public void onDestroy() {
		// adView.destroy();
		super.onDestroy();
		System.out
				.println("----------------onDestroy RadioVnMedia Activity---------------");
	}

	/**
	 * Fix bug: The content of the adapter has changed but ListView did not
	 * receive a notification
	 */

	protected void onStop() {
		super.onStop();
		m_listview.setVisibility(View.GONE);
	}

	/**
	 * Fix bug: The content of the adapter has changed but ListView did not
	 * receive a notification
	 */

	protected void onRestart() {
		super.onRestart();
		m_listview.setVisibility(View.VISIBLE);
	}

	public void onPause() {
		super.onPause();
		System.out
				.println("----------------onPause RadioVnMedia Activity---------------");
	}

	public void onResume() {
		super.onResume();
		if (NotifierHelper.sentNotificationPlaylist) {
			NotifierHelper.sentNotificationPlaylist = false;
			PlayerScreenActivity.backFromRadioVnMediaActivity = true;
			finish();
		}
		System.out
				.println("----------------onResume RadioVnMedia Activity---------------");
	}

	public void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_screen);

		System.out.println("Curernt state = " + int_current_state);
		if (HtmlEntity == null || HtmlEntity.size() == 0)
			HtmlEntity = load_HtmlEntity();
		try {
			readConfigResource();
		} catch (Exception e) {
			e.printStackTrace();
		}

		mDialog = new ProgressDialog(RadioVnMedia.this);
		m_listview = (ListView) findViewById(R.id.lv_danhsach);
		// registerForContextMenu(m_listview);
		m_listview.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				switch (int_current_state) {
				case STATE_TAB_CATEGORY:
					return false;
				case STATE_TAB_NEWEST:
					m_list_current_playlist.add(m_list_newest.get(pos));
					Toast.makeText(
							RadioVnMedia.this,
							"Added: \""
									+ m_list_newest.get(pos).get(KEY_LABEL_STR)
									+ "\" to playlist", Toast.LENGTH_SHORT)
							.show();
					NotifierHelper.sendNotification2(RadioVnMedia.this,
							RadioVnMedia.class,
							m_list_newest.get(pos).get(KEY_LABEL_STR)
									.toString(), m_list_current_playlist.size());
					break;
				case STATE_TAB_TOPHIT:
					m_list_current_playlist.add(m_list_tophit.get(pos));
					NotifierHelper.sendNotification2(RadioVnMedia.this,
							RadioVnMedia.class,
							m_list_tophit.get(pos).get(KEY_LABEL_STR)
									.toString(), m_list_current_playlist.size());
					Toast.makeText(
							RadioVnMedia.this,
							"Added: \""
									+ m_list_tophit.get(pos).get(KEY_LABEL_STR)
									+ "\" to playlist", Toast.LENGTH_SHORT)
							.show();
					break;
				case STATE_RADIO_TRACKS_LIST:
					m_list_current_playlist.add(m_list_subCategories.get(pos));
					NotifierHelper.sendNotification2(RadioVnMedia.this,
							RadioVnMedia.class, m_list_subCategories.get(pos)
									.get(KEY_LABEL_STR).toString(),
							m_list_current_playlist.size());
					Toast.makeText(
							RadioVnMedia.this,
							"Added: \""
									+ m_list_subCategories.get(pos).get(
											KEY_LABEL_STR) + "\" to playlist",
							Toast.LENGTH_SHORT).show();
					break;
				}
				return true;
			}
		});

		header_title = (TextView) findViewById(R.id.txt_header_title);
		page_info = (TextView) findViewById(R.id.txt_page_info);

		anim_switch_page_enter = AnimationUtils.loadAnimation(this,
				R.anim.popup_show);
		anim_switch_page_exit = AnimationUtils.loadAnimation(this,
				R.anim.popup_hide);
		layout_page_navigation_panel = (LinearLayout) findViewById(R.id.layout_switchpage);

		editbox_page_number = (EditText) findViewById(R.id.editbox_page_number);
		editbox_page_number.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				editbox_page_number.setText("");
				return false;
			}
		});
		editbox_page_number
				.setOnEditorActionListener(new OnEditorActionListener() {

					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE
								|| actionId == EditorInfo.IME_ACTION_GO
								|| actionId == EditorInfo.IME_ACTION_NEXT) {
							InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
							layout_page_navigation_panel
									.startAnimation(anim_switch_page_exit);
							layout_page_navigation_panel
									.setVisibility(View.GONE);
							editPageNumberDone(v.getText());
							return true;
						}
						return false;
					}
				});

		String[] from_category = { KEY_LABEL_STR };
		int[] to_category = { R.id.txt_item };

		String[] from_tophottrack = { KEY_LABEL_STR };
		int[] to_tophottrack = { R.id.txt_radio_title };

		String[] from_radiotracks = { KEY_LABEL_STR, KEY_LUOTNGHE_STR,
				KEY_THOILUONG_STR };
		int[] to_radiotracks = { R.id.txt_radio_title, R.id.txt_luotnghe,
				R.id.txt_thoiluong };
		// if (m_adapter_category == null)
		m_adapter_category = new SimpleAdapter(this, m_list_categories,
				R.layout.item_category, from_category, to_category);
		// if (m_adapter_subCategory == null)
		m_adapter_subCategory = new SimpleAdapter(this, m_list_subCategories,
				R.layout.item_radio_subtrack, from_radiotracks, to_radiotracks);
		// if (m_adapter_newest == null)
		m_adapter_newest = new SimpleAdapter(this, m_list_newest,
				R.layout.item_radio_track, from_tophottrack, to_tophottrack);
		// if (m_adapter_tophit == null)
		m_adapter_tophit = new SimpleAdapter(this, m_list_tophit,
				R.layout.item_radio_track, from_tophottrack, to_tophottrack);

		switch (int_current_state) {
		case STATE_TAB_CATEGORY:
			m_listview.setAdapter(m_adapter_category);
			break;
		case STATE_TAB_NEWEST:
			m_listview.setAdapter(m_adapter_newest);
			break;
		case STATE_TAB_TOPHIT:
			m_listview.setAdapter(m_adapter_tophit);
			break;
		case STATE_RADIO_TRACKS_LIST:
			m_listview.setAdapter(m_adapter_subCategory);
		}
		System.out.println("--------------------------------------");
		m_listview.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				if (layout_page_navigation_panel.isShown()) {
					layout_page_navigation_panel
							.startAnimation(anim_switch_page_exit);
					layout_page_navigation_panel.setVisibility(View.GONE);
				}
				return false;
			}
		});

		m_listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				onClick_ItemListView(arg0, arg1, arg2, arg3);
			}
		});

		Button tab_Category = (Button) findViewById(R.id.tab_chuyenmuc);
		Button tab_Newest = (Button) findViewById(R.id.tab_moinhat);
		Button tab_Tophit = (Button) findViewById(R.id.tab_noibat);

		switch (int_current_state) {
		case STATE_RADIO_TRACKS_LIST:
		case STATE_TAB_CATEGORY:
			tab_Category.requestFocus();
			break;
		case STATE_TAB_NEWEST:
			tab_Newest.requestFocus();
			break;
		case STATE_TAB_TOPHIT:
			tab_Tophit.requestFocus();
			break;
		}

		tab_Category.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus)
					onClick_TabCategory(v);
			}
		});
		tab_Newest.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus)
					onClick_TabNewest(v);
			}
		});
		tab_Tophit.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus)
					onClick_TabTopHit(v);
			}
		});

		if (string_HtmlContent == null) {
			loadDataFromURL(URL_HOME_PAGE);
		} else {
			new ProcessResourceHTML().execute();
		}

		AdView adView = new AdView(this, AdSize.BANNER, "a14f4361202bb4c");

		// Add the adView to it
		((LinearLayout) findViewById(R.id.ads_layout)).addView(adView,
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

		// Initiate a generic request to load it with an ad
		AdRequest request = new AdRequest();
		request.setTesting(true);

		adView.loadAd(request);
	}

	//
	// public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
	// menuInfo) {
	// super.onCreateContextMenu(menu, v, menuInfo);
	// switch (int_current_state) {
	// case STATE_TAB_TOPHIT:
	// case STATE_TAB_NEWEST:
	// case STATE_RADIO_TRACKS_LIST:
	// MenuInflater inflater = getMenuInflater();
	// inflater.inflate(R.menu.radio_track_options, menu);
	// break;
	// }
	// }

	//
	// public boolean onContextItemSelected(MenuItem item) {
	// switch(item.getItemId()){
	// case R.id.item_download:
	// case R.id.item_addplaylist:
	// }
	//
	// return true;
	// }

	public boolean onCreateOptionsMenu(Menu menu) {
		// switch (int_current_state) {
		// case STATE_TAB_TOPHIT:
		// case STATE_TAB_NEWEST:
		// case STATE_TAB_CATEGORY:
		// MenuInflater inflater = getMenuInflater();
		// inflater.inflate(R.menu.common_options, menu);
		// break;
		// }
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		Toast.makeText(this,
				getResources().getString(R.string.MSG_USER_MESSAGE),
				Toast.LENGTH_LONG).show();
		switch (item.getItemId()) {

		}
		return true;
	}

	private boolean checkPageNumberValid(String page_number) {
		try {
			int page = Integer.parseInt(page_number);
			if (page >= 1 && page <= int_total_pages
					&& !string_current_page.equals(page_number)) {
				return true;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return false;
	}

	private void editPageNumberDone(CharSequence page_number) {
		if (!checkPageNumberValid(page_number.toString())) {
			String string_page_number_format = getResources().getString(
					R.string.TEXT_FORMAT_PAGE_NUMBER);
			string_page_number_format = string_page_number_format.replace(
					"{CP}", string_current_page);
			string_page_number_format = string_page_number_format.replace(
					"{TP}", "" + int_total_pages);
			editbox_page_number.setText(string_page_number_format);
			return;
		}
		string_current_page = page_number.toString();
		editbox_page_number
				.setText(string_current_page + "/" + int_total_pages);
		loadDataFromURL(string_SubCategoryCurrentPageURL + _PAGE_ + page_number);
	}

	public void onClick_NextPage(View v) {
		int current_page_int = Integer.parseInt(string_current_page);
		if (current_page_int == int_total_pages)
			return;
		current_page_int++;
		string_current_page = "" + current_page_int;
		updatePageNumberEditBox();
		loadDataFromURL(string_SubCategoryCurrentPageURL + _PAGE_
				+ string_current_page);
	}

	public void onClick_EndPage(View v) {
		if (string_current_page.equals("" + int_total_pages))
			return;
		string_current_page = "" + int_total_pages;
		updatePageNumberEditBox();
		loadDataFromURL(string_SubCategoryCurrentPageURL + _PAGE_
				+ string_current_page);
	}

	public void onClick_PreviousPage(View v) {
		int current_page_int = Integer.parseInt(string_current_page);
		if (current_page_int == 1)
			return;
		current_page_int--;
		string_current_page = "" + current_page_int;
		updatePageNumberEditBox();
		loadDataFromURL(string_SubCategoryCurrentPageURL + _PAGE_
				+ string_current_page);
	}

	public void onClick_FirstPage(View v) {
		if (string_current_page.equals("1"))
			return;
		string_current_page = "1";
		editbox_page_number
				.setText(string_current_page + "/" + int_total_pages);
		loadDataFromURL(string_SubCategoryCurrentPageURL + _PAGE_
				+ string_current_page);
	}

	private void updatePageNumberEditBox() {
		String string_page_number_format = getResources().getString(
				R.string.TEXT_FORMAT_PAGE_NUMBER);
		string_page_number_format = string_page_number_format.replace("{CP}",
				string_current_page);
		string_page_number_format = string_page_number_format.replace("{TP}",
				"" + int_total_pages);
		editbox_page_number.setText(string_page_number_format);
	}

	public void onStart() {
		super.onStart();
	}

	private void readConfigResource() throws Exception {
		if (FF_open_chude != null) {
			FF_open_chude.clear();
			FF_close_chude.clear();
			FB_open_chude.clear();
			FB_close_chude.clear();

			FF_open_moinhat.clear();
			FF_close_moinhat.clear();
			FB_open_moinhat.clear();
			FB_close_moinhat.clear();

			FF_open_noibat.clear();
			FF_close_noibat.clear();
			FB_open_noibat.clear();
			FB_close_noibat.clear();
		}

		FF_open_radio_playing_image.clear();
		FF_close_radio_playing_image.clear();
		FB_open_radio_playing_image.clear();
		FB_close_radio_playing_image.clear();

		FF_open_radio_playing_media.clear();
		FF_close_radio_playing_media.clear();
		FB_open_radio_playing_media.clear();
		FB_close_radio_playing_media.clear();

		FF_open_radio_playing_description.clear();
		FF_close_radio_playing_description.clear();
		FB_open_radio_playing_description.clear();
		FB_close_radio_playing_description.clear();

		FF_open_radio_playing_luotnghe.clear();
		FF_close_radio_playing_luotnghe.clear();
		FB_open_radio_playing_luotnghe.clear();
		FB_close_radio_playing_luotnghe.clear();

		FF_open_radio_playing_name.clear();
		FF_close_radio_playing_name.clear();
		FB_open_radio_playing_name.clear();
		FB_close_radio_playing_name.clear();

		FF_open_totalpages.clear();
		FF_close_totalpages.clear();
		FB_open_totalpages.clear();
		FB_open_totalpages.clear();

		FF_open_totaltracks.clear();
		FF_close_totaltracks.clear();
		FB_open_totaltracks.clear();
		FB_open_totaltracks.clear();

		Properties properties = new Properties();
		properties.load(getResources()
				.openRawResource(R.raw.config_total_pages));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);

			if (ffopen == null)
				break;
			FF_open_totalpages.add(ffopen);
			FF_close_totalpages.add(ffclose);
		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_totalpages.add(fbopen);
			FB_close_totalpages.add(fbclose);
		}

		properties.clear();
		properties.load(getResources().openRawResource(
				R.raw.config_total_tracks));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);

			if (ffopen == null)
				break;
			FF_open_totaltracks.add(ffopen);
			FF_close_totaltracks.add(ffclose);
		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_totaltracks.add(fbopen);
			FB_close_totaltracks.add(fbclose);
		}

		properties.clear();
		properties.load(getResources().openRawResource(R.raw.config_chude));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);

			if (ffopen == null)
				break;
			FF_open_chude.add(ffopen);
			FF_close_chude.add(ffclose);

		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_chude.add(fbopen);
			FB_close_chude.add(fbclose);
		}
		properties.clear();
		properties.load(getResources().openRawResource(R.raw.config_moinhat));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_moinhat.add(ffopen);
			FF_close_moinhat.add(ffclose);

		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_moinhat.add(fbopen);
			FB_close_moinhat.add(fbclose);
		}
		properties.clear();
		properties.load(getResources().openRawResource(R.raw.config_noibat));
		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_noibat.add(ffopen);
			FF_close_noibat.add(ffclose);
		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_noibat.add(fbopen);
			FB_close_noibat.add(fbclose);
		}
		properties.clear();
		properties
				.load(getResources().openRawResource(R.raw.config_radiotrack));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_radiotrack.add(ffopen);
			FF_close_radiotrack.add(ffclose);

		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_radiotrack.add(fbopen);
			FB_close_radiotrack.add(fbclose);
		}
		properties.clear();
		// Read resource location for radio playing screen
		properties.load(getResources().openRawResource(
				R.raw.radio_playing_image_location));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_radio_playing_image.add(ffopen);
			FF_close_radio_playing_image.add(ffclose);

		}

		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_radio_playing_image.add(fbopen);
			FB_close_radio_playing_image.add(fbclose);
		}

		properties.clear();
		properties.load(getResources().openRawResource(
				R.raw.radio_playing_media_location));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_radio_playing_media.add(ffopen);
			FF_close_radio_playing_media.add(ffclose);

		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_radio_playing_media.add(fbopen);
			FB_close_radio_playing_media.add(fbclose);
		}
		properties.clear();
		properties.load(getResources().openRawResource(
				R.raw.radio_playing_description_location));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_radio_playing_description.add(ffopen);
			FF_close_radio_playing_description.add(ffclose);

		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_radio_playing_description.add(fbopen);
			FB_close_radio_playing_description.add(fbclose);
		}
		properties.clear();
		properties.load(getResources().openRawResource(
				R.raw.radio_playing_luotnghe_location));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_radio_playing_luotnghe.add(ffopen);
			FF_close_radio_playing_luotnghe.add(ffclose);

		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_radio_playing_luotnghe.add(fbopen);
			FB_close_radio_playing_luotnghe.add(fbclose);
		}
		properties.clear();
		properties.load(getResources().openRawResource(
				R.raw.radio_playing_name_location));

		for (int i = 0;; i++) {
			String ffopen = properties.getProperty(TAG_FF_OPEN + i);
			String ffclose = properties.getProperty(TAG_FF_CLOSE + i);
			if (ffopen == null)
				break;
			FF_open_radio_playing_name.add(ffopen);
			FF_close_radio_playing_name.add(ffclose);
		}
		for (int i = 0;; i++) {
			String fbopen = properties.getProperty(TAG_FB_OPEN + i);
			String fbclose = properties.getProperty(TAG_FB_CLOSE + i);
			if (fbopen == null)
				break;
			FB_open_radio_playing_name.add(fbopen);
			FB_close_radio_playing_name.add(fbclose);
		}
	}

	private void load_TabsContent(String html_content) {
		try {
			m_list_categories.clear();
			// Get chu de
			FindToFocus ff = new FindToFocus(FF_open_chude, FF_close_chude) {

				public void stringFocus(final String str) {

					RadioVnMedia.this.runOnUiThread(new Runnable() {

						public void run() {
							final HashMap<String, Object> item = new HashMap<String, Object>();
							FindBarrier fb = new FindBarrier(str,
									FB_open_chude, FB_close_chude) {

								public void stringResult(String str, int index) {
									switch (index) {
									case KEY_LINK_INT:
										item.put(KEY_LINK_STR, str);
										break;
									case KEY_LABEL_INT:
										str = StringUtils.trim(str);
										item.put(KEY_LABEL_STR, str);
										break;
									}
								}
							};
							fb.findBarrier();
							m_listview.requestLayout();
							item.put(KEY_SELECT_STR, false);
							m_list_categories.add(item);
							m_adapter_category.notifyDataSetChanged();
						}
					});
				}
			};
			ff.findFocus(html_content, 0);
			System.out.println("111111111111111111111111111111");
			// Get moi nhat
			m_list_newest.clear();
			ff = new FindToFocus(FF_open_moinhat, FF_close_moinhat) {

				public void stringFocus(final String str) {

					RadioVnMedia.this.runOnUiThread(new Runnable() {

						public void run() {
							final HashMap<String, Object> item = new HashMap<String, Object>();
							FindBarrier fb = new FindBarrier(str,
									FB_open_moinhat, FB_close_moinhat) {

								public void stringResult(String str, int index) {
									switch (index) {
									case KEY_LINK_INT:
										item.put(KEY_LINK_STR, str);
										break;
									case KEY_LABEL_INT:
										str = StringUtils.trim(str);
										try {
											str = HTMLUtils
													.convertHtmlCodeToUTF8(str);
										} catch (Exception e) {
											e.printStackTrace();
										}
										item.put(KEY_LABEL_STR, str);
										break;
									}
								}
							};
							fb.findBarrier();
							m_listview.requestLayout();
							item.put(KEY_SELECT_STR, false);
							m_list_newest.add(item);
							m_adapter_newest.notifyDataSetChanged();
						}
					});
				}
			};
			ff.findFocus(html_content, 0);
			System.out.println("22222222222222222222222222222222222222");
			// -----Noi bat----
			m_list_tophit.clear();
			ff = new FindToFocus(FF_open_noibat, FF_close_noibat) {

				public void stringFocus(final String str) {
					RadioVnMedia.this.runOnUiThread(new Runnable() {

						public void run() {
							final HashMap<String, Object> item = new HashMap<String, Object>();
							FindBarrier fb = new FindBarrier(str,
									FB_open_noibat, FB_close_noibat) {

								public void stringResult(String str, int index) {
									switch (index) {
									case KEY_LINK_INT:
										item.put(KEY_LINK_STR, str);
										break;
									case KEY_LABEL_INT:
										str = StringUtils.trim(str);
										try {
											str = HTMLUtils
													.convertHtmlCodeToUTF8(str);
										} catch (Exception e) {
											e.printStackTrace();
										}
										item.put(KEY_LABEL_STR, str);
										break;
									}
								}
							};
							fb.findBarrier();
							item.put(KEY_SELECT_STR, false);
							m_list_tophit.add(item);
							m_adapter_tophit.notifyDataSetChanged();
						}
					});
				}
			};

			ff.findFocus(html_content, 0);

			System.out.println("33333333333333333333333333333333333333");
			RadioVnMedia.this.runOnUiThread(new Runnable() {

				public void run() {
					header_title.setText(getResources().getString(
							R.string.TEXT_HEADER_TITLE));
					page_info.setText(getResources().getString(
							R.string.TEXT_HEADER_SUBTITLE));
				}
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void load_RadioTracks(String page_content) throws Exception {
		if (m_list_subCategories != null)
			m_list_subCategories.clear();
		else
			m_list_subCategories = new ArrayList<HashMap<String, Object>>();
		FindToFocus ff = new FindToFocus(FF_open_totalpages,
				FF_close_totalpages) {

			public void stringFocus(String str) {
				FindBarrier fb = new FindBarrier(str, FB_open_totalpages,
						FB_close_totalpages) {

					public void stringResult(String str, int index) {
						if (str != null) {
							str = StringUtils.trim(str);
							if (str.length() > 0)
								int_total_pages = Integer.parseInt(str);
						}
					}
				};
				fb.findBarrier();
			}
		};

		ff.findFocus(page_content, 0);
		ff = new FindToFocus(FF_open_totaltracks, FF_close_totaltracks) {

			public void stringFocus(final String string_focus) {
				FindBarrier fb = new FindBarrier(string_focus,
						FB_open_totaltracks, FB_close_totaltracks) {

					public void stringResult(String str, int index) {
						if (str != null) {
							str = StringUtils.trim(str);

							String format_subtitle = RadioVnMedia.this
									.getResources().getString(
											R.string.TEXT_SUBTITLE_SUBCATEGORY);
							format_subtitle = format_subtitle.replace("{CP}",
									string_current_page);
							format_subtitle = format_subtitle.replace("{TP}",
									"" + int_total_pages);
							final String subtitle = format_subtitle.replace(
									"{TT}", str);
							RadioVnMedia.this.runOnUiThread(new Runnable() {

								public void run() {
									header_title.setText(m_list_categories
											.get(int_CurrentCategoryIndex)
											.get(KEY_LABEL_STR).toString());
									page_info
											.setText(string_Header_SubTitle_SubCategory = subtitle);
									editbox_page_number
											.setText(string_current_page + "/"
													+ int_total_pages);
								}
							});
						}
					}
				};
				fb.findBarrier();
			}
		};

		ff.findFocus(page_content, 0);
		ff = new FindToFocus(FF_open_radiotrack, FF_close_radiotrack) {

			public void stringFocus(final String str) {

				RadioVnMedia.this.runOnUiThread(new Runnable() {

					public void run() {
						final HashMap<String, Object> item = new HashMap<String, Object>();
						FindBarrier fb = new FindBarrier(str,
								FB_open_radiotrack, FB_close_radiotrack) {

							public void stringResult(String str, int index) {
								str = StringUtils.trim(str);
								switch (index) {
								case KEY_LINK_INT:
									item.put(KEY_LINK_STR, str);
									break;
								case KEY_LABEL_INT:
									item.put(KEY_LABEL_STR, str);
									break;
								case KEY_THOILUONG_INT:
									item.put(KEY_THOILUONG_STR, str);
									break;
								case KEY_LUOTNGHE_INT:
									item.put(KEY_LUOTNGHE_STR, str);
								}
							}
						};
						fb.findBarrier();
						m_listview.requestLayout();
						item.put(KEY_SELECT_STR, false);
						m_list_subCategories.add(item);
						m_adapter_subCategory.notifyDataSetChanged();
					}
				});
			}
		};

		ff.findFocus(page_content, 0);
		System.out.println("-------------End load track info--------------");
	}

	private HashMap<String, String> load_HtmlEntity() {
		HashMap<String, String> map_character = new HashMap<String, String>();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				getResources().openRawResource(R.raw.html_entity)));
		String line;
		try {
			while ((line = br.readLine()) != null) {
				String[] part = line.split("\t");
				map_character.put(part[HTML_ENTITY], part[HTML_CHARACTER]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map_character;
	}

	protected void onSaveInstanceState(Bundle outState) {
		System.out.println("----------Saved Instance---------");
	}

	private long curentTimeMilisec = 0;

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (int_current_state) {
		case STATE_RADIO_TRACKS_LIST:
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if (layout_page_navigation_panel.isShown()) {
					layout_page_navigation_panel
							.startAnimation(anim_switch_page_exit);
					layout_page_navigation_panel.setVisibility(View.GONE);
				} else {
					isSubCategory = false;
					updateUIState(STATE_TAB_CATEGORY);
				}
				break;
			case KeyEvent.KEYCODE_MENU:
				if (layout_page_navigation_panel.isShown()) {
					layout_page_navigation_panel
							.startAnimation(anim_switch_page_exit);
					layout_page_navigation_panel.setVisibility(View.GONE);
				} else {
					layout_page_navigation_panel
							.startAnimation(anim_switch_page_enter);
					layout_page_navigation_panel.setVisibility(View.VISIBLE);
				}
				break;
			}
			return true;
		case STATE_TAB_CATEGORY:
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if (System.currentTimeMillis() - curentTimeMilisec > 300) {
					Toast.makeText(RadioVnMedia.this,
							"Double press BACK key to EXIT", Toast.LENGTH_SHORT)
							.show();
					curentTimeMilisec = System.currentTimeMillis();
				} else {
					PlayerScreenActivity.notifyExit = true;
					finish();
				}
			}
			return true;
		case STATE_TAB_TOPHIT:
		case STATE_TAB_NEWEST:
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if (System.currentTimeMillis() - curentTimeMilisec > 300) {
					Toast.makeText(RadioVnMedia.this,
							"Double press BACK key to EXIT", Toast.LENGTH_SHORT)
							.show();
					curentTimeMilisec = System.currentTimeMillis();
				} else {
					PlayerScreenActivity.notifyExit = true;
					finish();
				}
				break;
			case KeyEvent.KEYCODE_MENU:
				break;
			}
			return true;
		}

		return true;
	}

	private void setState(int state) {
		int_current_state = state;
		string_current_page = "1";
		if (int_current_state != STATE_RADIO_TRACKS_LIST
				&& layout_page_navigation_panel.isShown()) {
			layout_page_navigation_panel.startAnimation(anim_switch_page_exit);
			layout_page_navigation_panel.setVisibility(View.GONE);
		}
		System.out.println("Curernt state1 = " + int_current_state);
	}

	@SuppressWarnings("unused")
	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

	public void loadDataFromURL(String url) {
		System.out.println("URL: " + url);
		new DownloadResourceHTML().execute(url);
	}

	public class DownloadResourceHTML extends AsyncTask<String, Void, Void> {

		private String Error = null;

		protected void onPreExecute() {
			mDialog.setCancelable(false);
			mDialog.setMessage(getResources().getString(
					R.string.TEXT_DOWNLOADING_HTML_CODE));
			mDialog.show();
		}

		protected Void doInBackground(String... urls) {
			try {
				string_HtmlContent = new SrcGrabber().grabSource(urls[0]);
			} catch (Exception e) {
				e.printStackTrace();
				Error = e.getMessage();
				cancel(true);
			}
			return null;
		}

		protected void onPostExecute(Void unused) {
			// mDialog.dismiss();
			if (Error != null) {
				Toast.makeText(RadioVnMedia.this, Error, Toast.LENGTH_LONG)
						.show();
				mDialog.dismiss();
			} else {
				new ProcessResourceHTML().execute();
			}
		}
	}

	public class ProcessResourceHTML extends AsyncTask<Void, Void, Void> {
		private String Error = null;

		protected void onPreExecute() {
			mDialog.setCancelable(true);
			mDialog.setMessage(getResources().getString(
					R.string.MSG_PROCESSING_HTML_CODE));
			if (!mDialog.isShowing())
				mDialog.show();
		}

		protected Void doInBackground(Void... urls) {
			try {
				switch (int_current_state) {
				case STATE_TAB_CATEGORY:
				case STATE_TAB_NEWEST:
				case STATE_TAB_TOPHIT:
					System.out
							.println("-----------------load_TabsContent---------------------");
					load_TabsContent(string_HtmlContent);
					System.out
							.println("-----------------End load_TabsContent---------------------");
					break;
				case STATE_RADIO_TRACKS_LIST:
					System.out.println("------------Load subcategory-------");
					load_RadioTracks(string_HtmlContent);
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Error = e.getMessage();
				cancel(true);
			}

			return null;
		}

		protected void onPostExecute(Void unused) {
			mDialog.dismiss();
			if (Error != null) {
				Toast.makeText(RadioVnMedia.this, Error, Toast.LENGTH_LONG)
						.show();
			}
			RadioVnMedia.this.runOnUiThread(new Runnable() {

				public void run() {
					switch (int_current_state) {
					case STATE_TAB_CATEGORY:
						m_adapter_category.notifyDataSetChanged();
						break;
					case STATE_TAB_NEWEST:
						m_adapter_newest.notifyDataSetChanged();
						break;
					case STATE_TAB_TOPHIT:
						m_adapter_tophit.notifyDataSetChanged();
						break;
					case STATE_RADIO_TRACKS_LIST:
						m_adapter_subCategory.notifyDataSetChanged();
						break;
					}
				}
			});
		}
	}

	private void onClick_ItemListView(AdapterView<?> adapter, View v,
			int position, long arg3) {

		switch (int_current_state) {
		case STATE_TAB_CATEGORY:
			setState(STATE_RADIO_TRACKS_LIST);
			try {
				isSubCategory = true;
				int_CurrentCategoryIndex = position;
				m_listview.setAdapter(m_adapter_subCategory);
				loadDataFromURL((string_SubCategoryCurrentPageURL = URL_HEAD_CHUYENMUC
						+ m_list_categories.get(position).get(KEY_LINK_STR))
						+ _PAGE_ + string_current_page);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case STATE_TAB_NEWEST:
			m_list_current_playlist.clear();
			page_info.setText("");
			isSubCategory = false;
			PlayerScreenActivity.media_link = null;
			PlayerScreenActivity.backFromRadioVnMediaActivity = true;
			m_list_current_playlist.add(m_list_newest.get(position));
			finish();
			break;
		case STATE_TAB_TOPHIT:
			m_list_current_playlist.clear();
			page_info.setText("");
			isSubCategory = false;
			PlayerScreenActivity.media_link = null;
			PlayerScreenActivity.backFromRadioVnMediaActivity = true;
			m_list_current_playlist.add(m_list_tophit.get(position));
			finish();
			break;
		case STATE_RADIO_TRACKS_LIST:
			m_list_current_playlist.clear();
			isSubCategory = true;
			PlayerScreenActivity.media_link = null;
			PlayerScreenActivity.backFromRadioVnMediaActivity = true;
			m_list_current_playlist.add(m_list_subCategories.get(position));
			finish();
			break;
		}
	}

	public void updateUIState(int state) {
		setState(state);
		switch (state) {
		case STATE_TAB_CATEGORY:
			m_listview.setAdapter(m_adapter_category);
			header_title.setText(getResources().getString(
					R.string.TEXT_HEADER_TITLE));
			page_info.setText(getResources().getString(
					R.string.TEXT_HEADER_SUBTITLE));
			break;
		case STATE_TAB_NEWEST:
			m_listview.setAdapter(m_adapter_newest);
			header_title.setText(getResources().getString(
					R.string.TEXT_HEADER_TITLE));
			page_info.setText(getResources().getString(
					R.string.TEXT_HEADER_SUBTITLE));
			break;
		case STATE_TAB_TOPHIT:
			m_listview.setAdapter(m_adapter_tophit);
			header_title.setText(getResources().getString(
					R.string.TEXT_HEADER_TITLE));
			page_info.setText(getResources().getString(
					R.string.TEXT_HEADER_SUBTITLE));
			break;
		case STATE_RADIO_TRACKS_LIST:
			m_listview.setAdapter(m_adapter_subCategory);
			if (int_CurrentCategoryIndex < m_list_categories.size())
				header_title.setText(m_list_categories
						.get(int_CurrentCategoryIndex).get(KEY_LABEL_STR)
						.toString());
			page_info.setText(string_Header_SubTitle_SubCategory);
			break;
		}
	}

	private static boolean isSubCategory = false;
	private static String string_Header_SubTitle_SubCategory;

	public void onClick_TabCategory(View button_ChuDe) {
		updateUIState(isSubCategory ? STATE_RADIO_TRACKS_LIST
				: STATE_TAB_CATEGORY);
	}

	public void onClick_TabNewest(View button_MoiNhat) {
		updateUIState(STATE_TAB_NEWEST);
	}

	public void onClick_TabTopHit(View button_NoiBat) {
		updateUIState(STATE_TAB_TOPHIT);
	}
}